// 初始化变量
let restaurantData = [];
let currentScrapeJob = null;
let restaurantLinks = []; // 存储餐厅详情页链接
let currentRestaurantIndex = 0; // 当前处理的餐厅索引
let contentScriptReady = false; // 跟踪content script是否已加载
let isPaused = false; // 是否暂停爬取
let popupWindowId = null; // 存储popup窗口ID

// 监听扩展图标点击事件
chrome.action.onClicked.addListener(function () {
  // 检查是否已经有打开的窗口
  if (popupWindowId !== null) {
    // 如果已经有窗口，则聚焦到该窗口
    chrome.windows.update(popupWindowId, { focused: true });
  } else {
    // 创建一个新窗口
    chrome.windows.create(
      {
        url: chrome.runtime.getURL('popup.html'),
        type: 'popup',
        width: 400,
        height: 600,
        focused: true,
      },
      function (window) {
        popupWindowId = window.id;
      }
    );
  }
});

// 监听窗口关闭事件
chrome.windows.onRemoved.addListener(function (windowId) {
  if (windowId === popupWindowId) {
    popupWindowId = null;
  }
});

// 监听来自popup和content script的消息
chrome.runtime.onMessage.addListener(function (message, sender, sendResponse) {
  if (message.action === 'startScrape') {
    startScraping(
      message.url,
      message.pages,
      message.delay || 2000,
      message.sortByReviews
    );
  } else if (message.action === 'exportData') {
    exportToExcel();
  } else if (message.action === 'contentScriptReady') {
    // 标记content script已准备就绪
    contentScriptReady = true;
    console.log('Content script is ready');
  } else if (message.action === 'pauseScrape') {
    // 暂停爬取
    isPaused = true;
    console.log('Scraping paused');
    chrome.runtime.sendMessage({
      action: 'scrapeStatusUpdate',
      message: `爬取已暂停，当前已爬取 ${restaurantData.length} 条数据`,
    });
    sendResponse({ success: true, paused: true });
  } else if (message.action === 'resumeScrape') {
    // 继续爬取
    if (currentScrapeJob && currentScrapeJob.tabId) {
      isPaused = false;
      console.log('Scraping resumed');
      chrome.runtime.sendMessage({
        action: 'scrapeStatusUpdate',
        message: '继续爬取...',
      });

      // 继续处理当前任务
      if (currentScrapeJob.phase === 'collectLinks') {
        // 如果在收集链接阶段暂停，继续获取下一页
        chrome.scripting
          .executeScript({
            target: { tabId: currentScrapeJob.tabId },
            function: getNextPageUrl,
          })
          .then((urlResult) => {
            const nextPageUrl = urlResult[0].result;
            if (nextPageUrl) {
              // 导航到下一页
              chrome.tabs.update(currentScrapeJob.tabId, { url: nextPageUrl });
            } else {
              // 没有下一页，开始抓取详情
              startScrapeDetails(currentScrapeJob.tabId);
            }
          });
      } else if (currentScrapeJob.phase === 'scrapeDetails') {
        // 如果在抓取详情阶段暂停，继续处理当前餐厅
        chrome.tabs.update(currentScrapeJob.tabId, {
          url: restaurantLinks[currentRestaurantIndex],
        });
      }

      sendResponse({ success: true, resumed: true });
    } else {
      sendResponse({ success: false, error: '没有正在进行的爬取任务' });
    }
  } else if (message.action === 'getScrapeStatus') {
    // 获取当前爬取状态
    sendResponse({
      isRunning: !!currentScrapeJob,
      isPaused: isPaused,
      dataCount: restaurantData.length,
      progress: currentScrapeJob
        ? {
            phase: currentScrapeJob.phase,
            current:
              currentScrapeJob.phase === 'collectLinks'
                ? currentScrapeJob.currentPage
                : currentRestaurantIndex,
            total:
              currentScrapeJob.phase === 'collectLinks'
                ? currentScrapeJob.totalPages
                : restaurantLinks.length,
          }
        : null,
    });
  }
});

// 开始抓取过程
async function startScraping(startUrl, totalPages, delay, sortByReviews) {
  try {
    // 重置数据
    restaurantData = [];
    restaurantLinks = [];
    currentRestaurantIndex = 0;

    // 创建抓取任务
    currentScrapeJob = {
      totalPages: totalPages,
      currentPage: 0,
      baseUrl: startUrl,
      delay: delay,
      sortByReviews: sortByReviews, // 保存排序选项
      phase: 'collectLinks', // 第一阶段：收集餐厅链接
    };

    // 打开第一个标签页进行抓取
    const tab = await chrome.tabs.create({ url: startUrl, active: false });
    currentScrapeJob.tabId = tab.id;

    // 监听标签页更新
    chrome.tabs.onUpdated.addListener(tabUpdateListener);
  } catch (error) {
    console.error('Scraping startup error:', error);
    chrome.runtime.sendMessage({
      action: 'scrapeError',
      error: error.message,
    });
  }
}

// 标签页更新监听器
function tabUpdateListener(tabId, changeInfo, tab) {
  if (!currentScrapeJob || tabId !== currentScrapeJob.tabId) return;

  if (changeInfo.status === 'complete') {
    // 页面加载完成，根据当前阶段执行不同的操作
    setTimeout(() => {
      // 直接执行抓取阶段，不再滚动页面
      executeScrapingPhase(tabId);
    }, currentScrapeJob.delay); // 使用自定义延迟
  }
}

// 执行当前抓取阶段的函数
function executeScrapingPhase(tabId) {
  if (currentScrapeJob.phase === 'collectLinks') {
    // 第一阶段：收集餐厅链接
    collectRestaurantLinks(tabId);
  } else if (currentScrapeJob.phase === 'scrapeDetails') {
    // 第二阶段：抓取餐厅详情
    scrapeRestaurantDetails(tabId);
  }
}

// 收集餐厅链接
function collectRestaurantLinks(tabId) {
  // 如果处于暂停状态，不执行抓取
  if (isPaused) {
    console.log('Link collection is paused');
    return;
  }

  chrome.scripting
    .executeScript({
      target: { tabId: tabId },
      function: getRestaurantLinks,
    })
    .then((results) => {
      if (results && results[0] && results[0].result) {
        // 将本页的餐厅链接添加到列表中
        const pageLinks = results[0].result;
        restaurantLinks = restaurantLinks.concat(pageLinks);

        // 更新进度
        currentScrapeJob.currentPage++;
        chrome.runtime.sendMessage({
          action: 'scrapeProgress',
          current: currentScrapeJob.currentPage,
          total: currentScrapeJob.totalPages,
          phase: 'Collecting restaurant links',
        });

        // 检查是否需要继续收集链接
        if (currentScrapeJob.currentPage < currentScrapeJob.totalPages) {
          // 如果处于暂停状态，不继续抓取下一页
          if (isPaused) {
            console.log(
              'Link collection paused after page:',
              currentScrapeJob.currentPage
            );
            return;
          }

          // 获取下一页URL
          chrome.scripting
            .executeScript({
              target: { tabId: tabId },
              function: getNextPageUrl,
            })
            .then((urlResult) => {
              const nextPageUrl = urlResult[0].result;
              if (nextPageUrl) {
                // 导航到下一页
                chrome.tabs.update(tabId, { url: nextPageUrl });
              } else {
                // 没有下一页，开始抓取详情
                startScrapeDetails(tabId);
              }
            });
        } else {
          // 已达到指定页数，开始抓取详情
          startScrapeDetails(tabId);
        }
      }
    })
    .catch((error) => {
      console.error('Script execution error:', error);
      chrome.runtime.sendMessage({
        action: 'scrapeError',
        error: error.message,
      });
      cleanupScraping();
    });
}

// 开始抓取餐厅详情
function startScrapeDetails(tabId) {
  if (restaurantLinks.length === 0) {
    // 没有找到餐厅链接
    chrome.runtime.sendMessage({
      action: 'scrapeError',
      error: 'No restaurant links found',
    });
    cleanupScraping();
    return;
  }

  // 如果处于暂停状态，不开始抓取详情
  if (isPaused) {
    console.log('Scraping is paused before starting details collection');
    chrome.runtime.sendMessage({
      action: 'scrapeStatusUpdate',
      message: `已暂停。找到 ${restaurantLinks.length} 家餐厅，等待继续...`,
    });
    return;
  }

  // 更新抓取阶段
  currentScrapeJob.phase = 'scrapeDetails';
  currentRestaurantIndex = 0;

  // 发送状态更新
  chrome.runtime.sendMessage({
    action: 'scrapeStatusUpdate',
    message: `Found ${restaurantLinks.length} restaurants. Starting to collect details...`,
  });

  // 导航到第一个餐厅详情页
  chrome.tabs.update(tabId, { url: restaurantLinks[0] });
}

// 抓取餐厅详情
function scrapeRestaurantDetails(tabId) {
  // 如果处于暂停状态，不执行抓取
  if (isPaused) {
    console.log('Scraping is paused');
    return;
  }

  chrome.scripting
    .executeScript({
      target: { tabId: tabId },
      function: getRestaurantDetails,
    })
    .then((results) => {
      if (results && results[0] && results[0].result) {
        // 添加餐厅详情到数据列表
        const restaurantDetail = results[0].result;
        restaurantData.push(restaurantDetail);

        // 更新进度
        currentRestaurantIndex++;
        const percentage =
          (currentRestaurantIndex / restaurantLinks.length) * 100;

        chrome.runtime.sendMessage({
          action: 'scrapeProgress',
          current: currentRestaurantIndex,
          total: restaurantLinks.length,
          phase: 'Collecting restaurant details',
        });

        // 保存当前数据
        chrome.storage.local.set({ restaurantData: restaurantData });

        // 检查是否还有餐厅需要抓取
        if (currentRestaurantIndex < restaurantLinks.length) {
          // 如果处于暂停状态，不继续抓取下一个
          if (isPaused) {
            console.log(
              'Scraping paused after processing restaurant:',
              currentRestaurantIndex - 1
            );
            return;
          }

          // 导航到下一个餐厅详情页
          chrome.tabs.update(tabId, {
            url: restaurantLinks[currentRestaurantIndex],
          });
        } else {
          // 所有餐厅都已抓取完成
          finishScraping();
        }
      }
    })
    .catch((error) => {
      console.error('Script execution error:', error);
      // 如果抓取单个餐厅失败，继续下一个
      currentRestaurantIndex++;

      // 如果处于暂停状态，不继续抓取下一个
      if (isPaused) {
        console.log('Scraping paused after error');
        return;
      }

      if (currentRestaurantIndex < restaurantLinks.length) {
        chrome.tabs.update(tabId, {
          url: restaurantLinks[currentRestaurantIndex],
        });
      } else {
        finishScraping();
      }
    });
}

// 完成抓取过程
function finishScraping() {
  chrome.runtime.sendMessage({
    action: 'scrapeComplete',
    count: restaurantData.length,
  });

  // 自动导出数据
  setTimeout(() => {
    exportToExcel();
  }, 1000);

  cleanupScraping();
}

// 清理抓取资源
function cleanupScraping() {
  if (currentScrapeJob && currentScrapeJob.tabId) {
    chrome.tabs.remove(currentScrapeJob.tabId);
    chrome.tabs.onUpdated.removeListener(tabUpdateListener);
    currentScrapeJob = null;
  }
}

// 导出数据为Excel
function exportToExcel() {
  chrome.storage.local.get('restaurantData', function (result) {
    if (!result.restaurantData || result.restaurantData.length === 0) {
      chrome.runtime.sendMessage({
        action: 'scrapeError',
        error: 'No data to export',
      });
      return;
    }

    // 创建CSV内容
    let csvContent = 'data:text/csv;charset=utf-8,\uFEFF'; // 添加BOM标记解决中文乱码

    // 添加标题行 - 使用中英文表头
    csvContent +=
      '餐厅名称 (Restaurant Name),电话 (Phone),评论数量 (Review Count)\n';

    // 添加数据行
    result.restaurantData.forEach((restaurant) => {
      // 确保数据存在且格式正确
      const name = restaurant.name
        ? restaurant.name.replace(/"/g, '""')
        : 'Unknown';
      const phone = restaurant.phone
        ? restaurant.phone.replace(/"/g, '""')
        : 'Unknown';
      const reviewCount = restaurant.reviewCount
        ? restaurant.reviewCount.toString()
        : 'Unknown';

      const row = [`"${name}"`, `"${phone}"`, `"${reviewCount}"`].join(',');
      csvContent += row + '\n';
    });

    // 创建下载链接
    const encodedUri = encodeURI(csvContent);
    const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
    const filename = `yelp-restaurants-${timestamp}.csv`;

    // 下载文件
    chrome.downloads.download({
      url: encodedUri,
      filename: filename,
      saveAs: true,
    });

    // 发送导出成功消息
    chrome.runtime.sendMessage({
      action: 'scrapeStatusUpdate',
      message: `已成功导出 ${result.restaurantData.length} 条餐厅数据`,
    });
  });
}

// 在搜索结果页面中执行的函数，获取餐厅链接
function getRestaurantLinks() {
  const links = [];

  // 获取所有餐厅列表项
  const listItems = document.querySelectorAll('[data-testid="serp-ia-card"]');

  // 如果没有找到标准列表项，尝试其他选择器
  const alternativeItems =
    listItems.length > 0
      ? listItems
      : document.querySelectorAll(
          '.container__09f24__mpR8_ .padding-t3__09f24__TMrIW.padding-r3__09f24__1pBFG'
        );

  // 遍历每个餐厅项，提取链接
  alternativeItems.forEach((item) => {
    try {
      // 尝试多种选择器获取链接
      const linkElement =
        item.querySelector('a[data-font-weight="semibold"]') ||
        item.querySelector('h3 a') ||
        item.querySelector('.css-1m051bw') ||
        item.querySelector('a[href^="/biz/"]');

      if (linkElement && linkElement.href) {
        // 确保是完整的URL
        const href = linkElement.href;
        if (href.includes('/biz/')) {
          links.push(href);
        }
      }
    } catch (e) {
      console.error('Error extracting restaurant link:', e);
    }
  });

  return links;
}

// 在餐厅详情页面中执行的函数，获取详细信息
function getRestaurantDetails() {
  try {
    console.log('Starting to extract restaurant details');

    // 获取餐厅名称
    const nameElement = document.querySelector('h1');
    const name = nameElement ? nameElement.textContent.trim() : 'Unknown Name';
    console.log('Restaurant name:', name);

    // 获取电话 - 使用提供的DOM结构
    let phone = 'Unknown Phone';

    // 尝试从"Phone number"部分获取电话
    const phoneSection = Array.from(
      document.querySelectorAll('.y-css-1bi7ba5')
    ).find((el) => el.textContent.includes('Phone number'));

    if (phoneSection) {
      console.log('Found "Phone number" section');
      const phoneElement = phoneSection
        .closest('.y-css-13akgjv')
        .querySelector('.y-css-19xonnr[data-font-weight="semibold"]');
      if (phoneElement) {
        phone = phoneElement.textContent.trim();
        console.log('Found phone using primary selector:', phone);
      }
    }

    // 如果没有找到电话号码，尝试其他方法
    if (phone === 'Unknown Phone') {
      // 尝试查找包含电话号码格式的文本
      console.log('Searching for phone number patterns');

      // 首先尝试查找带有电话图标的元素
      const phoneIconElements = document.querySelectorAll(
        'svg[aria-hidden="true"]'
      );
      for (const iconEl of phoneIconElements) {
        const parentEl = iconEl.closest('div');
        if (parentEl) {
          const possiblePhoneEl =
            parentEl.querySelector('p') || parentEl.nextElementSibling;
          if (possiblePhoneEl) {
            const text = possiblePhoneEl.textContent.trim();
            if (
              /\(\d{3}\) \d{3}-\d{4}/.test(text) ||
              /\d{3}-\d{3}-\d{4}/.test(text)
            ) {
              phone = text;
              console.log('Found phone near icon:', phone);
              break;
            }
          }
        }
      }

      // 如果仍未找到，尝试在页面中查找电话号码格式
      if (phone === 'Unknown Phone') {
        const allParagraphs = document.querySelectorAll('p, div, span');
        for (const el of allParagraphs) {
          const text = el.textContent.trim();
          if (
            /\(\d{3}\) \d{3}-\d{4}/.test(text) ||
            /\d{3}-\d{3}-\d{4}/.test(text) ||
            /\+1 \d{3}-\d{3}-\d{4}/.test(text)
          ) {
            phone = text;
            console.log('Found phone using pattern matching:', phone);
            break;
          }
        }
      }

      // 如果仍未找到，尝试其他常见选择器
      if (phone === 'Unknown Phone') {
        console.log('Trying alternative phone selectors');
        const altPhoneElement =
          document.querySelector('[href^="tel:"]') ||
          document.querySelector('[data-testid="phone-number"]') ||
          document.querySelector('.phone') ||
          document.querySelector('[itemprop="telephone"]');

        if (altPhoneElement) {
          phone = altPhoneElement.textContent.trim();
          console.log('Found phone using alternative selector:', phone);
        }
      }

      // 最后尝试从页面URL中提取商家ID，记录未找到电话的情况
      if (phone === 'Unknown Phone') {
        console.log('Could not find phone number for this restaurant');
        const businessId = window.location.pathname
          .split('/')
          .filter((p) => p)
          .pop();
        console.log('Business ID from URL:', businessId);
      }
    }

    // 清理电话号码格式，只保留数字和常见分隔符
    if (phone !== 'Unknown Phone') {
      // 提取电话号码中的数字和常见分隔符
      const phoneMatch = phone.match(
        /(\+?1?\s*[-.]?\s*)?(\(\d{3}\)\s*|\d{3}[-\s.]?)\d{3}[-\s.]?\d{4}/
      );
      if (phoneMatch) {
        phone = phoneMatch[0].trim();
      }
    }

    // 获取评论数量
    let reviewCount = 'Unknown';

    // 尝试从页面中提取评论数量
    const reviewCountElement = document.querySelector(
      '[data-testid="reviews-count"]'
    );
    if (reviewCountElement) {
      const text = reviewCountElement.textContent.trim();
      const match = text.match(/\d+/);
      if (match) {
        reviewCount = match[0];
        console.log('Found review count:', reviewCount);
      }
    }

    // 如果没有找到评论数量，尝试其他选择器
    if (reviewCount === 'Unknown') {
      // 尝试查找包含"reviews"或"评论"的文本
      const reviewElements = Array.from(
        document.querySelectorAll('p, div, span, a')
      ).filter(
        (el) =>
          el.textContent.includes('reviews') || el.textContent.includes('评论')
      );

      for (const el of reviewElements) {
        const text = el.textContent.trim();
        const match = text.match(/(\d+)\s*(reviews|评论)/i);
        if (match) {
          reviewCount = match[1];
          console.log(
            'Found review count using alternative selector:',
            reviewCount
          );
          break;
        }
      }
    }

    // 返回餐厅详情（包含名称、电话和评论数量）
    const result = {
      name: name,
      phone: phone,
      reviewCount: reviewCount,
    };

    console.log('Final extracted data:', result);
    return result;
  } catch (e) {
    console.error('Error parsing restaurant details:', e);
    return {
      name: 'Error',
      phone: 'Error',
      reviewCount: 'Error',
    };
  }
}

// 获取下一页URL的函数
function getNextPageUrl() {
  // 尝试多种可能的下一页按钮选择器
  const nextButton =
    document.querySelector('a[aria-label="下一页"]') ||
    document.querySelector('a[aria-label="Next"]') ||
    document.querySelector('a.next-link') ||
    document.querySelector('a.pagination-links_anchor[href*="start="]') ||
    document.querySelector('.next-link');

  // 如果找不到明确的下一页按钮，尝试查找分页链接
  if (!nextButton) {
    const paginationLinks = document.querySelectorAll('.pagination-link');
    const currentPage = document.querySelector('.pagination-link--current');

    if (currentPage && paginationLinks.length > 0) {
      const currentIndex = Array.from(paginationLinks).indexOf(currentPage);
      if (currentIndex >= 0 && currentIndex < paginationLinks.length - 1) {
        const nextPageUrl = paginationLinks[currentIndex + 1].href;

        // 确保保留排序参数
        if (
          nextPageUrl &&
          !nextPageUrl.includes('sortby=') &&
          window.location.href.includes('sortby=review_count')
        ) {
          // 如果下一页URL不包含排序参数但当前页面有，则添加排序参数
          const url = new URL(nextPageUrl);
          url.searchParams.append('sortby', 'review_count');
          return url.toString();
        }

        return nextPageUrl;
      }
    }
  }

  if (nextButton) {
    const nextPageUrl = nextButton.href;

    // 确保保留排序参数
    if (
      nextPageUrl &&
      !nextPageUrl.includes('sortby=') &&
      window.location.href.includes('sortby=review_count')
    ) {
      // 如果下一页URL不包含排序参数但当前页面有，则添加排序参数
      const url = new URL(nextPageUrl);
      url.searchParams.append('sortby', 'review_count');
      return url.toString();
    }

    return nextPageUrl;
  }

  return null;
}
